package com.future.order.controller;

import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Locale;

/**
 * @author weber
 * @Description: 国际化
 * @Date 2025/8/5 15:43
 */
@RestController
@RequestMapping("/national")
public class InternationalizationController {

    @Autowired
    private MessageSource messageSource;

    @GetMapping("/greeting")
    public String greeting() {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
        String language = request.getHeader("Accept-Language");
        Locale locale = Locale.forLanguageTag(language);
        locale = locale != null ? locale : LocaleContextHolder.getLocale();
        return messageSource.getMessage("greeting.message", null, locale);
    }

    @GetMapping("/greeting-v2")
    public String getNationalization(@RequestHeader(value = "Accept-Language",required = false) Locale locale) {

        if (locale == null) {
            locale = Locale.getDefault();
        }
        return messageSource.getMessage("greeting.message", null, locale);
    }

}
